﻿Public Class QuestionDetail
    Inherits ItemDetailPage

    Protected Property QuestionID() As ULong

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        QuestionID = CULng(Request.QueryString.Get("ID"))
        If Not IsPostBack Then
            If Not QuestionID AndAlso Request.QueryString.Get("Action") = "Add" Then
                If InsertionPermitted Then
                    DetailFormView.DefaultMode = FormViewMode.Insert
                Else
                    StopEditing()
                End If
            ElseIf QuestionID AndAlso QuestionExists(QuestionID) Then
                If Request.QueryString.Get("Action") = "Edit" Then
                    If ModificationPermitted Then
                        DetailFormView.DefaultMode = FormViewMode.Edit
                        UpdateDataSource()
                    Else
                        StopEditing()
                    End If
                Else
                    DetailFormView.DefaultMode = FormViewMode.ReadOnly
                    UpdateDataSource()
                End If
            Else
                RedirectToList()
            End If
        End If
    End Sub

    Protected Sub SaveButton_Click(sender As Object, e As EventArgs)
        If ModificationPermitted Then
            Dim questionGateway As New QuestionGateway()
            Dim title As TextBox = DetailFormView.FindControl("TitleTextBox")
            Dim description As TextBox = DetailFormView.FindControl("DescriptionTextBox")
            questionGateway.Update(QuestionID, title.Text, description.Text)
            UpdateTags()
            StopEditing()
        End If
    End Sub

    Protected Sub CancelEditButton_Click(sender As Object, e As EventArgs)
        StopEditing()
    End Sub

    Protected Sub EditButton_Click(sender As Object, e As EventArgs)
        StartEditing()
    End Sub

    Protected Sub DeleteButton_Click(sender As Object, e As EventArgs)
        If ModificationPermitted Then
            Dim gateway As New QuestionGateway()
            gateway.DeleteByID(QuestionID)
            RedirectToList()
        End If
    End Sub

    Protected Sub SubmitButton_Click(sender As Object, e As EventArgs)
        If InsertionPermitted Then
            Dim gateway As New QuestionGateway()
            Dim title As TextBox = DetailFormView.FindControl("TitleTextBox")
            Dim description As TextBox = DetailFormView.FindControl("DescriptionTextBox")
            QuestionID = gateway.Insert(title.Text, description.Text, GetCurrentUserID())
            UpdateTags()
            StopEditing()
        End If
    End Sub

    Protected Sub UpdateTags()
        Dim tagGateway As New QuestionTagGateway()
        Dim tags As TextBox = DetailFormView.FindControl("TagTextBox")
        tagGateway.Update(QuestionID, New ArrayList(tags.Text.Split(",")), GetCurrentUserID())
    End Sub

    Protected Function QuestionExists(ByVal ID As ULong) As Boolean
        Dim gateway As New QuestionGateway()
        Return gateway.Exists(ID)
    End Function

    Protected Overrides ReadOnly Property UserHasOwnership() As Boolean
        Get
            Dim gateway As New QuestionGateway()
            Return gateway.HasOwnership(QuestionID, User.Identity.Name)
        End Get
    End Property

    Protected Sub StartEditing()
        Dim redirectUrl As String = String.Format("~/Pages/QuestionDetail.aspx?ID={0}&Action=Edit", QuestionID)
        Response.Redirect(redirectUrl)
    End Sub

    Protected Sub StopEditing()
        Dim redirectUrl As String = String.Format("~/Pages/QuestionDetail.aspx?ID={0}", QuestionID)
        Response.Redirect(redirectUrl)
    End Sub

    Protected Sub RedirectToList()
        Dim redirectUrl As String = String.Format("~/Pages/QuestionList.aspx")
        Response.Redirect(redirectUrl)
    End Sub

    Protected Function getPhotoPath(ByVal fileName As String) As String
        Return PhotoUtils.getNormalPath(fileName)
    End Function

    Protected Sub UpdateDataSource()
        Dim questionGateway As New QuestionGateway()
        DetailFormView.DataSource = questionGateway.FindByID(QuestionID)
        DetailFormView.DataBind()

        Dim nestedView As ListView = DetailFormView.FindControl("NestedDetailListView")
        If nestedView IsNot Nothing Then
            Dim answerGateway As New AnswerGateway()
            nestedView.DataSource = answerGateway.FindByID(QuestionID)
            nestedView.DataBind()
        End If
    End Sub

    Protected Sub AnswerRating_Changed(sender As Object, e As AjaxControlToolkit.RatingEventArgs)
        Dim userGateway As New SiteUserGateway()
        Dim ratingGateway As New AnswerRatingGateway()
        Dim answerID As ULong = CULng(e.Tag)
        Dim userID As ULong = GetCurrentUserID()
        Dim rating As Integer = CInt(e.Value)
        ratingGateway.InsertOrUpdate(answerID, userID, rating)
    End Sub

    Protected Function GetStarCssClass(ByVal answerID As ULong) As String
        Dim cssClass As String = "ratingStar"
        If IsRatingPermitted(answerID) Then
            cssClass &= " editableStar"
        End If
        Return cssClass
    End Function

    ''' <summary>
    ''' Returns True if user is permitted to rate content
    ''' </summary>
    ''' <returns>Boolean</returns>
    ''' <remarks>
    ''' Rating is permitted on an Item if user has authenticated successfully and is not
    ''' the owner of the Iten. I.e. the owner cannot rate his/her own posts.
    ''' </remarks>
    Protected Function IsRatingPermitted(ByVal answerID As ULong) As Boolean
        Dim gateway As New AnswerGateway()
        Dim userHasOwnership As Boolean = gateway.HasOwnership(answerID, User.Identity.Name)
        Return Roles.IsUserInRole("Member") And Not userHasOwnership
    End Function

    Protected Function GetQuestionTagsCSV(ByVal questionID As ULong) As String
        Dim gateway As New QuestionTagGateway()
        Dim tags As ArrayList = gateway.GetQuestionTagsList(questionID)
        Return Join(tags.ToArray(), ", ")
    End Function

    Protected Function GetQuestionTags(ByVal questionID As ULong) As DataTable
        Dim gateway As New QuestionTagGateway()
        Return gateway.FindQuestionTags(questionID)
    End Function


    Protected Sub TagEditLinkButton_Click(sender As Object, e As EventArgs)
        DetailFormView.FindControl("TagRepeater").Visible = False
        DetailFormView.FindControl("TagEditLinkButton").Visible = False
        DetailFormView.FindControl("TagTextBox").Visible = True
        DetailFormView.FindControl("TagSaveLinkButton").Visible = True
        DetailFormView.FindControl("TagEditCancelLinkButton").Visible = True
    End Sub

    Protected Sub TagSaveLinkButton_Click(sender As Object, e As EventArgs)
        If TaggingPermitted Then
            UpdateTags()
            StopEditing()
        End If
    End Sub

    Protected Sub TagEditCancelLinkButton_Click(sender As Object, e As EventArgs)
        StopEditing()
    End Sub

End Class